﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media.Imaging;
using System.Linq;
using Microsoft.Phone;
using IkeCode.WP7.Toolkit;

namespace IkeCode.WP7.HQReader.Base
{
    /// <summary>
    /// Helper for MediaLibrary of Windows Phone
    /// </summary>
    public class IcMediaLibraryHelper
    {
        /// <summary>
        /// Get image from MediaLibrary
        /// </summary>
        /// <param name="imageGuid">Image guid (like as name)</param>
        /// <returns>BitmapImage</returns>
        public static BitmapImage GetImage(Guid imageName)
        {
            var bitmap = new BitmapImage();
            var mediaLibrary = new MediaLibrary();

            var pic = mediaLibrary.SavedPictures.FirstOrDefault(i => i.Name.Contains(imageName.ToString()));
            if (pic != null)
            {
                bitmap.SetSource(pic.GetImage());
            }

            return bitmap;
        }

        /// <summary>
        /// Get image from MediaLibrary
        /// </summary>
        /// <param name="imageGuid">Image guid (like as name)</param>
        /// <returns>BitmapImage</returns>
        public static BitmapImage GetImage(string imageName)
        {
            var bitmap = new BitmapImage();
            var mediaLibrary = new MediaLibrary();

            var pic = mediaLibrary.SavedPictures.FirstOrDefault(i => i.Name.Contains(imageName));
            if (pic != null)
            {
                bitmap.SetSource(pic.GetImage());
            }

            return bitmap;
        }

        /// <summary>
        /// Save image to MediaLibrary
        /// </summary>
        /// <param name="image">BitmapImage object</param>
        /// <returns>BitmapImage</returns>
        public static BitmapImage SaveImage(string imageName, BitmapImage image)
        {
            var mediaLibrary = new MediaLibrary();
            var wbm = new WriteableBitmap(image);
            Picture pic = mediaLibrary.SavePicture(imageName, wbm.GetBytes());

            return image;
        }
    }
}
